package com.yl.users.services.impl

import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.common.ErrorCode
import com.yl.common.Flag
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.users.entity.SysCompany
import com.yl.users.entity.SysTableFieldPerm
import com.yl.users.mapper.*
import com.yl.users.pojo.dto.CompanyPermissionsDto
import com.yl.users.pojo.vo.SysCompanySelectVo
import com.yl.users.services.ISysCompanyService
import com.yl.users.services.ISystemService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
class SystemServiceImpl (
	private val sysTableFieldPermMapper: SysTableFieldPermMapper,
	private val sysCompanyMapper: SysCompanyMapper,
	private val sysPermissionsMapper: SysPermissionsMapper
):ISystemService {

	@Autowired
	lateinit var iSysCompanyService: ISysCompanyService

	override fun getCompanyList(sysCompany: SysCompanySelectVo): List<SysCompany> {
		return sysCompanyMapper.selectCompanyList(sysCompany)
	}

	override fun getCompanyPage(page: Page<SysCompany>,sysCompany: SysCompanySelectVo): Page<SysCompany> {
		return sysCompanyMapper.selectCompanyPage(page,sysCompany)
	}

	override fun addCompany(sysCompany: SysCompany): ResponseBody {

			if (sysCompany.name == null || sysCompany.name.isNullOrEmpty()) {
				return returnError(ErrorCode.PARAM_EMPTY, "请输入公司名称")
			}
			sysCompany.createTime = Date()
			sysCompany.updateTime = Date()
			sysCompany.flag = Flag.NEW_ADD
			if (sysCompany.superId == null) {
				sysCompany.superId = 0
			}
			sysCompanyMapper.insert(sysCompany)
			val addDefaultTopDept = iSysCompanyService.addDefaultTopDept(sysCompany.id)
			if (addDefaultTopDept.code != ErrorCode.SUCCESS.code) {
				return addDefaultTopDept
			}
			return returnSuccess()

	}

	override fun getPermList(): MutableList<CompanyPermissionsDto> {
		return sysPermissionsMapper.selectAllPermissionsList()
	}


	override fun fieldList(sysTableFieldPerm: SysTableFieldPerm): List<SysTableFieldPerm> {
		return sysTableFieldPermMapper.selectList(Wrappers.query(sysTableFieldPerm))
	}

	override fun fieldPage(
		page: Page<SysTableFieldPerm>,
		sysTableFieldPerm: SysTableFieldPerm
	): Page<SysTableFieldPerm> {
		return sysTableFieldPermMapper.selectPage(page, Wrappers.query(sysTableFieldPerm))
	}

	override fun fieldTree(): ResponseBody {
		return returnSuccess(
			sysTableFieldPermMapper.selectFieldTree()
		)
	}

	override fun addField(sysTableFieldPerm: SysTableFieldPerm) {
		sysTableFieldPermMapper.insert(sysTableFieldPerm)
	}

}